package com.guli.order.messageQueue;

import com.guli.common.constant.OrderConstant;
import com.guli.common.to.SecKillOrderInfoTo;
import com.guli.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/*
 * @Author 罗俊
 * @date 2020/12/2 - 10:21 下午
 *
 */
@Component
@Slf4j
@RabbitListener(queues = {OrderConstant.SEC_KILL_CREATE_ORDER_QUEUE})
public class CreateOrder {

    @Resource
    OrderService orderService;

    @RabbitHandler
    public void createOrderByOrderSn(SecKillOrderInfoTo secKillOrderInfoTo, Channel channel, Message message) {
        log.info("即将创建订单：{}", secKillOrderInfoTo);

        try {
            orderService.submitOrder(secKillOrderInfoTo.getOrderSn(),
                    secKillOrderInfoTo.getMemberId(),
                    secKillOrderInfoTo.getSpuId(),
                    secKillOrderInfoTo.getSkuId(),
                    secKillOrderInfoTo.getCount(),
                    secKillOrderInfoTo.getPrice()
            );

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("已为秒杀订单创建具体订单，订单号是：{}，具体信息是{}", secKillOrderInfoTo.getOrderSn(), secKillOrderInfoTo);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
                log.error("为秒杀订单号 orderSn = {}创建具体订单失败", secKillOrderInfoTo.getOrderSn());
                e.printStackTrace();

            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

    }
}
